﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Se.Framework.Common.ObjectRegistrySupport;
using Se.Framework.Web;
using Se.Framework.Web.Mvc;

namespace Trust.Casas.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            RegistryInitializer.RegisterAll(typeof(Trust.Casas.Model.TrustContextRepository<>));
            GlobalConfiguration.Configuration.DependencyResolver = new ObjectRegistryDependencyResolver(GlobalConfiguration.Configuration.DependencyResolver);
            GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new ObjectRegistryControllerSelector(GlobalConfiguration.Configuration));
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            var handler = Context.Handler as MvcHandler;
            if (handler != null)
            {
                object routeCulture = handler.RequestContext.RouteData != null ? handler.RequestContext.RouteData.Values["culture"] : null;

                CultureInfo cultureInfo = null;
                try
                {
                    cultureInfo = new CultureInfo(routeCulture != null ? routeCulture.ToString() : "es");
                }
                catch
                {
                    cultureInfo = new CultureInfo("es");
                }

                Thread.CurrentThread.CurrentUICulture = cultureInfo;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
            }
        }
    }
}